<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML
><HEAD
><TITLE
>A Complete Trigger Example</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.1.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Triggers"
HREF="triggers.html"><LINK
REL="PREVIOUS"
TITLE="Writing Trigger Functions in C"
HREF="trigger-interface.html"><LINK
REL="NEXT"
TITLE="The Rule System"
HREF="rules.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2011-12-01T22:07:59"></HEAD
><BODY
CLASS="SECT1"
><DIV
CLASS="NAVHEADER"
><TABLE
SUMMARY="Header navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TH
COLSPAN="5"
ALIGN="center"
VALIGN="bottom"
><A
HREF="index.html"
>PostgreSQL 9.1.2 Documentation</A
></TH
></TR
><TR
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
TITLE="Writing Trigger Functions in C"
HREF="trigger-interface.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="10%"
ALIGN="left"
VALIGN="top"
><A
HREF="triggers.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="60%"
ALIGN="center"
VALIGN="bottom"
>Chapter 36. Triggers</TD
><TD
WIDTH="20%"
ALIGN="right"
VALIGN="top"
><A
TITLE="The Rule System"
HREF="rules.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
></TABLE
><HR
ALIGN="LEFT"
WIDTH="100%"></DIV
><DIV
CLASS="SECT1"
><H1
CLASS="SECT1"
><A
NAME="TRIGGER-EXAMPLE"
>36.4. A Complete Trigger Example</A
></H1
><P
>    Here is a very simple example of a trigger function written in C.
    (Examples of triggers written in procedural languages can be found
    in the documentation of the procedural languages.)
   </P
><P
>    The function <CODE
CLASS="FUNCTION"
>trigf</CODE
> reports the number of rows in the
    table <TT
CLASS="STRUCTNAME"
>ttest</TT
> and skips the actual operation if the
    command attempts to insert a null value into the column
    <TT
CLASS="STRUCTFIELD"
>x</TT
>. (So the trigger acts as a not-null constraint but
    doesn't abort the transaction.)
   </P
><P
>    First, the table definition:
</P><PRE
CLASS="PROGRAMLISTING"
>CREATE TABLE ttest (
    x integer
);</PRE
><P>
   </P
><P
>    This is the source code of the trigger function:
</P><PRE
CLASS="PROGRAMLISTING"
>#include "postgres.h"
#include "executor/spi.h"       /* this is what you need to work with SPI */
#include "commands/trigger.h"   /* ... and triggers */

#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif

extern Datum trigf(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(trigf);

Datum
trigf(PG_FUNCTION_ARGS)
{
    TriggerData *trigdata = (TriggerData *) fcinfo-&#62;context;
    TupleDesc   tupdesc;
    HeapTuple   rettuple;
    char       *when;
    bool        checknull = false;
    bool        isnull;
    int         ret, i;

    /* make sure it's called as a trigger at all */
    if (!CALLED_AS_TRIGGER(fcinfo))
        elog(ERROR, "trigf: not called by trigger manager");

    /* tuple to return to executor */
    if (TRIGGER_FIRED_BY_UPDATE(trigdata-&#62;tg_event))
        rettuple = trigdata-&#62;tg_newtuple;
    else
        rettuple = trigdata-&#62;tg_trigtuple;

    /* check for null values */
    if (!TRIGGER_FIRED_BY_DELETE(trigdata-&#62;tg_event)
        &#38;&#38; TRIGGER_FIRED_BEFORE(trigdata-&#62;tg_event))
        checknull = true;

    if (TRIGGER_FIRED_BEFORE(trigdata-&#62;tg_event))
        when = "before";
    else
        when = "after ";

    tupdesc = trigdata-&#62;tg_relation-&#62;rd_att;

    /* connect to SPI manager */
    if ((ret = SPI_connect()) &#60; 0)
        elog(ERROR, "trigf (fired %s): SPI_connect returned %d", when, ret);

    /* get number of rows in table */
    ret = SPI_exec("SELECT count(*) FROM ttest", 0);

    if (ret &#60; 0)
        elog(ERROR, "trigf (fired %s): SPI_exec returned %d", when, ret);

    /* count(*) returns int8, so be careful to convert */
    i = DatumGetInt64(SPI_getbinval(SPI_tuptable-&#62;vals[0],
                                    SPI_tuptable-&#62;tupdesc,
                                    1,
                                    &#38;isnull));

    elog (INFO, "trigf (fired %s): there are %d rows in ttest", when, i);

    SPI_finish();

    if (checknull)
    {
        SPI_getbinval(rettuple, tupdesc, 1, &#38;isnull);
        if (isnull)
            rettuple = NULL;
    }

    return PointerGetDatum(rettuple);
}</PRE
><P>
   </P
><P
>    After you have compiled the source code (see <A
HREF="xfunc-c.html#DFUNC"
>Section 35.9.6</A
>), declare the function and the triggers:
</P><PRE
CLASS="PROGRAMLISTING"
>CREATE FUNCTION trigf() RETURNS trigger
    AS '<TT
CLASS="REPLACEABLE"
><I
>filename</I
></TT
>'
    LANGUAGE C;

CREATE TRIGGER tbefore BEFORE INSERT OR UPDATE OR DELETE ON ttest
    FOR EACH ROW EXECUTE PROCEDURE trigf();

CREATE TRIGGER tafter AFTER INSERT OR UPDATE OR DELETE ON ttest
    FOR EACH ROW EXECUTE PROCEDURE trigf();</PRE
><P>
   </P
><P
>    Now you can test the operation of the trigger:
</P><PRE
CLASS="SCREEN"
>=&gt; INSERT INTO ttest VALUES (NULL);
INFO:  trigf (fired before): there are 0 rows in ttest
INSERT 0 0

-- Insertion skipped and AFTER trigger is not fired

=&gt; SELECT * FROM ttest;
 x
---
(0 rows)

=&gt; INSERT INTO ttest VALUES (1);
INFO:  trigf (fired before): there are 0 rows in ttest
INFO:  trigf (fired after ): there are 1 rows in ttest
                                       ^^^^^^^^
                             remember what we said about visibility.
INSERT 167793 1
vac=&gt; SELECT * FROM ttest;
 x
---
 1
(1 row)

=&gt; INSERT INTO ttest SELECT x * 2 FROM ttest;
INFO:  trigf (fired before): there are 1 rows in ttest
INFO:  trigf (fired after ): there are 2 rows in ttest
                                       ^^^^^^
                             remember what we said about visibility.
INSERT 167794 1
=&gt; SELECT * FROM ttest;
 x
---
 1
 2
(2 rows)

=&gt; UPDATE ttest SET x = NULL WHERE x = 2;
INFO:  trigf (fired before): there are 2 rows in ttest
UPDATE 0
=&gt; UPDATE ttest SET x = 4 WHERE x = 2;
INFO:  trigf (fired before): there are 2 rows in ttest
INFO:  trigf (fired after ): there are 2 rows in ttest
UPDATE 1
vac=&gt; SELECT * FROM ttest;
 x
---
 1
 4
(2 rows)

=&gt; DELETE FROM ttest;
INFO:  trigf (fired before): there are 2 rows in ttest
INFO:  trigf (fired before): there are 1 rows in ttest
INFO:  trigf (fired after ): there are 0 rows in ttest
INFO:  trigf (fired after ): there are 0 rows in ttest
                                       ^^^^^^
                             remember what we said about visibility.
DELETE 2
=&gt; SELECT * FROM ttest;
 x
---
(0 rows)</PRE
><P>

   </P
><P
>    There are more complex examples in
    <TT
CLASS="FILENAME"
>src/test/regress/regress.c</TT
> and
    in <A
HREF="contrib-spi.html"
>spi</A
>.
   </P
></DIV
><DIV
CLASS="NAVFOOTER"
><HR
ALIGN="LEFT"
WIDTH="100%"><TABLE
SUMMARY="Footer navigation table"
WIDTH="100%"
BORDER="0"
CELLPADDING="0"
CELLSPACING="0"
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
><A
HREF="trigger-interface.html"
ACCESSKEY="P"
>Prev</A
></TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="index.html"
ACCESSKEY="H"
>Home</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
><A
HREF="rules.html"
ACCESSKEY="N"
>Next</A
></TD
></TR
><TR
><TD
WIDTH="33%"
ALIGN="left"
VALIGN="top"
>Writing Trigger Functions in C</TD
><TD
WIDTH="34%"
ALIGN="center"
VALIGN="top"
><A
HREF="triggers.html"
ACCESSKEY="U"
>Up</A
></TD
><TD
WIDTH="33%"
ALIGN="right"
VALIGN="top"
>The Rule System</TD
></TR
></TABLE
></DIV
></BODY
></HTML
>